//
//  ARMineBlockLIstOrFollowListViewModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/23.
//

import Foundation

class ARMineBlockListOrFollowListViewModel {
    
    let operationType: ARMineBlockLIstOrFollowListController.OperationType
    
    private var _dataSource: [ARUserModel] = []
    var dataSource: [ARUserModel] {
        _dataSource
    }
    
    init(operationType: ARMineBlockLIstOrFollowListController.OperationType) {
        self.operationType = operationType
    }
    
    func loadData(_ completion: @escaping (Error?) -> Void) {
        guard let userId = ARUserManager.shared.userId else {
            return
        }
        switch operationType {
        case .blockList:
            ARDataCenter.default.blackListFor(userId) { [weak self] list, err in
                if let err = err {
                    completion(err)
                    return
                }
                ARHelper.afterAsyncInMainQueue {
                    self?._dataSource.removeAll()
                    self?._dataSource.append(contentsOf: list)
                    completion(nil)
                }
            }
        case .followList:
            ARDataCenter.default.followListFor(userId) { [weak self] list, err in
                if let err = err {
                    completion(err)
                    return
                }
                ARHelper.afterAsyncInMainQueue {
                    self?._dataSource.removeAll()
                    self?._dataSource.append(contentsOf: list)
                    completion(nil)
                }
            }
        }
    }
    
    func operationAction(_ userId: String, completion: @escaping (Error?) -> Void) {
        switch operationType {
        case .blockList:
            ARDataCenter.default.addOrRemoveBlackList(userId, addOrRemove: false) { [weak self] err in
                ARHelper.afterAsyncInMainQueue {
                    if err == nil {
                        self?._dataSource.removeAll(where: { $0.userId == userId })
                    }
                    completion(err)
                }
            }
        case .followList:
            ARDataCenter.default.followOrUnfollowUser(userId, followOrUnfollow: false) { [weak self] err in
                ARHelper.afterAsyncInMainQueue {
                    if err == nil {
                        self?._dataSource.removeAll(where: { $0.userId == userId })
                    }
                    completion(err)
                }
            }
        }
    }
    
}
